def singleton(cls):
    _instance = {}
    
    def inner():
        # 以类地址作为键，实例作为值，每次创建时，首先查看该类是否存在实例
        if cls not in _instance:
            _instance[cls] = cls()
        return _instance[cls]
    
    return inner


@singleton
class GlobalResource(object):
    """实例化为单例"""
    def __init__(self):
        self.session = None
        self.redis = None
        self.scheduler = None
        

# class GlobalResource2(object):
#     """实例化为单例方法2"""
#     _instance = None
#
#     def __new__(cls, *args, **kwargs):
#         if cls._instance is None:
#             cls._instance = object.__new__(cls, *args, **kwargs)
#         return cls._instance
#
#     def __init__(self):
#         self.session = None
#         self.redis = None
#         self.scheduler = None


def global_handler(**kwargs):
    def _wraps(cls):
        for key, values in kwargs.items():
            setattr(cls, key, values)
        return cls
    return _wraps


@global_handler(g=GlobalResource)
class Base:
    _instance = None
    
    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
    
    @property
    def session(self):
        return g.session
    
    @property
    def redis(self):
        return g.redis


def check_data(schema, data):
    errors = schema.validate(data)
    for k, v in errors.items():
        for i in v:
            # print("{}{}".format(k, i))
            msg = "{}{}".format(k, i)
            return msg
            
            
class CustomException(Exception):
    """异常类重写"""
    def __init__(self, message, status_code):
        super().__init__(message, status_code)
        self.message = message
        self.status_code = status_code
